import mongoose from 'mongoose';
import { envConfig } from './environment';
import { log } from './logger';

export const connectDB = async (): Promise<void> => {
  try {
    const conn = await mongoose.connect(envConfig.mongodbUri);
    
    log.info(`MongoDB Connected: ${conn.connection.host}`);
    log.info(`Database: ${conn.connection.name}`);
    
    // 监听连接事件
    mongoose.connection.on('error', (error) => {
      log.error('MongoDB connection error:', error);
    });

    mongoose.connection.on('disconnected', () => {
      log.warn('MongoDB disconnected');
    });

    // 优雅关闭
    process.on('SIGINT', async () => {
      await mongoose.connection.close();
      log.info('MongoDB connection closed through app termination');
      process.exit(0);
    });

  } catch (error) {
    log.error('Error connecting to MongoDB:', error);
    process.exit(1);
  }
};

export default mongoose;